<?php
using("Db_Common_PreparedStatement");
using("Db_Common_SqlException");
using("Db_Adodb_ResultSet");

get(Libs_Catalog::fetch("adodb/adodb.inc"));
get(Libs_Catalog::fetch("adodb/adodb-exceptions.inc"));
/**
 * Implements the common prepared statement interface
 *
 * @package junction.db.adodb
 * @author Alexander Schearer <aas11@duke.edu>
 */
class Db_Adodb_PreparedStatement implements Db_Common_PreparedStatement {
	
	/**
	 * Database handle
	 *
	 * @var ADOConnection
	 */
	private $_dbh;
	
	/**
	 * Query statement
	 *
	 * @var String
	 */
	private $_statement;

	/**
	 * Prepared statement constructor.
	 * 
	 * @param string SQL query.
	 */
	public function __construct(ADOConnection & $conn, $sql) {
		$this->_dbh = $conn;
		$this->_statement = $sql;
	}
	
	/**
	 * Execute a SELECT prepared statement.
	 * 
	 * @see Db_Common_PreparedStatement::executeSelect()
	 * 
	 * @throws Db_Common_SqlException
	 * @param array SQL parameters.
	 * @return Db_Common_ResultSet
	 */
	public function executeSelect(array $params = null) {
		try {
			return new Db_Adodb_ResultSet($this->_dbh->Execute($this->_statement, $params), $this->_statement);
		} catch (Exception $e) {
			throw new Db_Common_SqlException($e->getMessage(), $this->_statement);
		}
	}

	/**
	 * Execute a non SELECT prepared statement.
	 * 
	 * @see Db_Common_PreparedStatement::executeSave()
	 * 
	 * @throws Db_Common_SqlException
	 * @param array SQL parameters.
	 * @return boolean
	 */	
	public function executeSave(array $params = null) {
		try {
			return $this->_dbh->Execute($this->_statement, $params);
		} catch (Exception $e) {
			throw new Db_Common_SqlException($e->getMessage(), $this->_statement);
		}
	}
	
	/**
	 * Return the query associated with this statement
	 * 
	 * @see Db_Common_PreparedStatement::getQuery()
	 *
	 * @return String
	 */
	public function getQuery() {
		return $this->_statement;
	}
	
	public function affectedRows() {
		return $this->_dbh->Affected_Rows();
	}
	
	public function lastInsertId() {
		return $this->_dbh->Insert_ID();
	}
}
?>